package com.doform.android.xianggucheng.activity.downorder;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.doform.android.xianggucheng.R;
import com.doform.android.xianggucheng.activity.BaseTitleActivity;
import com.doform.android.xianggucheng.bean.GuidBean;
import com.doform.android.xianggucheng.bean.ShopCarBean;
import com.doform.android.xianggucheng.popwindow.CommonDialog;
import com.doform.android.xianggucheng.retrofit.ApiSpecTransformer.DialogTransformer;
import com.doform.android.xianggucheng.retrofit.subscriber.ErrorHandleSubscriber;
import com.doform.android.xianggucheng.retrofit.HttpManager;
import com.doform.android.xianggucheng.utils.KeyBoardUtils;
import com.doform.android.xianggucheng.utils.TsUtils;
import com.doform.android.xianggucheng.widget.DividerItemDecoration;
import com.orhanobut.logger.Logger;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

import static com.doform.android.xianggucheng.R.id.et_number;

/**
 * Created by Administrator on 2017/5/10.
 */

public class ListShopCarActivity extends BaseTitleActivity {

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    @BindView(R.id.tv_empty)
    TextView mEmpty;

    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;

    @BindView(R.id.rl)
    LinearLayout mRl;

    @BindView(R.id.tv_sum_num)
    TextView mSumNum;

    private CommonAdapter<ShopCarBean.ListBean> mCommonAdapter;
    private CommonDialog mPopwindowNumber, mPopwindowPrice;
    private EditText etPopNumber;
    private TextView popAddNum;
    private TextView popReduceNum;
    private Button popCancleNum;
    private Button popSubmitNum;
    private String popNumStr;
    private Button mPopSubmitPrice;
    private Button mPopCanclePrice;
    private Button mPopReducePrice;
    private Button mPopAddPrice;
    private EditText popPrice;
    private EditText etPopPrice;
    private String popPriceStr;
    private boolean isNext = false;

    @Override
    protected void showView() {
        titleBar.setTextTitle("购物车");
    }

    @Override
    protected int layoutResId() {
        return R.layout.activity_shop_car;
    }

    @Override
    protected void init() {
        if (mPopwindowNumber == null) {
            mPopwindowNumber = new CommonDialog(this, R.layout.pop_computer);
        }

        if (mPopwindowPrice == null) {
            mPopwindowPrice = new CommonDialog(this, R.layout.pop_computer);
        }


    }

    @Override
    protected void initView() {

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

        etPopNumber = mPopwindowNumber.getView(et_number);
        popAddNum = mPopwindowNumber.getView(R.id.btn_add_num);
        popReduceNum = mPopwindowNumber.getView(R.id.btn_reduce_num);
        popCancleNum = mPopwindowNumber.getView(R.id.btn_pop_cancle);
        popSubmitNum = mPopwindowNumber.getView(R.id.btn_pop_submit);

        etPopPrice = mPopwindowPrice.getView(et_number);
        mPopAddPrice = mPopwindowPrice.getView(R.id.btn_add_num);
        mPopReducePrice = mPopwindowPrice.getView(R.id.btn_reduce_num);
        mPopCanclePrice = mPopwindowPrice.getView(R.id.btn_pop_cancle);
        mPopSubmitPrice = mPopwindowPrice.getView(R.id.btn_pop_submit);

    }

    private List<ShopCarBean.ListBean> mDatas = new ArrayList();

    @Override
    protected void onStart() {
        super.onStart();
        getDataForService();
    }

    private void getDataForService() {
        HttpManager.instance()
                .getShopCarData("1")
                .compose(new DialogTransformer<ShopCarBean>(mProgressBar))
                .subscribe(new ErrorHandleSubscriber<ShopCarBean>() {
                    @Override
                    public void onNext(@NonNull ShopCarBean shopCarBean) {
                        parseData(shopCarBean.getList());
                        if (TextUtils.isEmpty(shopCarBean.getTotal() + "")) {
                            isNext = false;
                            mSumNum.setText("总计 ：￥0");
                        } else {
                            isNext = true;
                            mSumNum.setText("总计 ：￥" + shopCarBean.getTotal());
                        }
                    }
                });
    }

    private void parseData(List<ShopCarBean.ListBean> data) {
        mDatas.clear();
        mDatas.addAll(data);
        if (mCommonAdapter != null) {
            mCommonAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void initListener() {
        initListView();
        popAddNum.setOnClickListener(this);
        popReduceNum.setOnClickListener(this);
        popSubmitNum.setOnClickListener(this);
        popCancleNum.setOnClickListener(this);

        mPopAddPrice.setOnClickListener(this);
        mPopReducePrice.setOnClickListener(this);
        mPopSubmitPrice.setOnClickListener(this);
        mPopCanclePrice.setOnClickListener(this);

        mPopwindowNumber.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                KeyBoardUtils.closeKeybord(etPopNumber, ListShopCarActivity.this);
            }
        });

        mPopwindowPrice.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                KeyBoardUtils.closeKeybord(etPopPrice, ListShopCarActivity.this);
            }
        });


    }

    private void initListView() {

        mCommonAdapter = new CommonAdapter<ShopCarBean.ListBean>(this, R.layout.activity_shop_car_item, mDatas) {
            @Override
            protected void convert(ViewHolder vh, final ShopCarBean.ListBean dataBean, final int position) {

                TextView name = vh.getView(R.id.tv_name);
                TextView type = vh.getView(R.id.tv_type);
                final EditText et_number = vh.getView(R.id.et_number);
                Button tv_add_num = vh.getView(R.id.btn_add_num);
                Button tv_reduce_num = vh.getView(R.id.btn_reduce_num);

                final EditText et_price = vh.getView(R.id.et_price);
                Button btn_add_price = vh.getView(R.id.btn_add_price);
                Button btn_reduce_price = vh.getView(R.id.btn_reduce_price);

                name.setText(dataBean.getName());
                type.setText("(" + dataBean.getMunit() + ")");
                et_number.setText(dataBean.getNum());
                et_price.setText(dataBean.getPrice());

                tv_add_num.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String trim = et_number.getText().toString().trim();
                        double v1 = Double.valueOf(trim) + 1;
                        postDataToService(dataBean, String.valueOf(v1), "");
                    }
                });

                btn_add_price.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String trim = et_price.getText().toString().trim();
                        if (TextUtils.isEmpty(trim)) {
                            trim = "0";
                        }
                        double v1 = Double.parseDouble(trim) + 1;

                        postDataToService(dataBean, "", String.valueOf(v1));
                    }
                });

                tv_reduce_num.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String trim = et_number.getText().toString().trim();
                        if (TextUtils.isEmpty(trim)) {
                            trim = "0";
                        }
                        double v1 = Double.parseDouble(trim) - 1;
                        if (v1 <= 0) {
                            TsUtils.showToast("当前数量已为最小值");
                            return;
                        }

                        postDataToService(dataBean, String.valueOf(v1), "");
                    }
                });

                btn_reduce_price.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String trim = et_price.getText().toString().trim();
                        if (trim == null || TextUtils.isEmpty(trim)) {
                            trim = "0";
                        }
                        double v1 = Double.parseDouble(trim) - 1;
                        if (v1 <= -1) {
                            Logger.v(v1 + "");
                            TsUtils.showToast("当前价格已为最小值");
                            return;
                        }
                        postDataToService(dataBean, "", String.valueOf(v1));
                    }
                });

                et_price.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopwindowPrice.show();
                        computPrice(dataBean);
                    }
                });

                et_number.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopwindowNumber.show();
                        computCar(dataBean);
                    }
                });

                vh.getView(R.id.btn_delete).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showDeleteItem(dataBean);
                    }
                });
            }
        };

        mRecyclerView.setAdapter(mCommonAdapter);

    }

    private void computPrice(final ShopCarBean.ListBean dataBean) {

        KeyBoardUtils.openKeybord(etPopPrice, this);

        etPopPrice.setText(dataBean.getPrice());
        etPopPrice.setFocusableInTouchMode(true);
        etPopPrice.requestFocus();
        etPopPrice.setSelection(dataBean.getPrice().length());

        popPriceStr = etPopPrice.getText().toString().trim();

        popPrice1 = Double.parseDouble(popPriceStr);
//        添加
        mPopAddPrice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popPrice2 = popPrice1 + 1;
                etPopPrice.setText(popPrice2 + "");
                popPrice1 = popPrice2;
                popPrice2 = 0;
            }
        });
//
        mPopReducePrice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popPrice1 <= 0) {
                    TsUtils.showToast("当前价格已为最小值");
                    return;
                }
                popPrice2 = popPrice1 - 1;
                etPopPrice.setText(popPrice2 + "");
                popPrice1 = popPrice2;
                popPrice2 = 0;
            }
        });

        mPopSubmitPrice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopwindowPrice.dismiss();
//                上传服务器
                popPriceStr = etPopPrice.getText().toString().trim();
                popPrice1 = Double.parseDouble(popPriceStr);
                postDataToService(dataBean, "", String.valueOf(popPrice1));
            }
        });

        mPopCanclePrice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopwindowPrice.dismiss();
            }
        });
    }

    private double popNum1 = 0;
    private double popNum2 = 0;
    private double popPrice1 = 0;
    private double popPrice2 = 0;

    private void computCar(final ShopCarBean.ListBean bean) {
        KeyBoardUtils.openKeybord(etPopNumber, this);
        etPopNumber.setText(bean.getNum());

        etPopNumber.setFocusableInTouchMode(true);
        etPopNumber.requestFocus();
        etPopNumber.setSelection(bean.getNum().length());

        popNumStr = etPopNumber.getText().toString().trim();
        popNum1 = Double.parseDouble(popNumStr);
//        添加
        popAddNum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popNum2 = popNum1 + 1;
                etPopNumber.setText(popNum2 + "");
                popNum1 = popNum2;
                popNum2 = 0;
            }
        });
//        减少
        popReduceNum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popNum1 <= 1) {
                    TsUtils.showToast("当前数量已为最小值");
                    return;
                }
                popNum2 = popNum1 - 1;
                etPopNumber.setText(popNum2 + "");
                popNum1 = popNum2;
                popNum2 = 0;
            }
        });

        popSubmitNum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopwindowNumber.dismiss();

                popNumStr = etPopNumber.getText().toString().trim();

                popNum1 = Double.parseDouble(popNumStr);
//                上传服务器
                postDataToService(bean, String.valueOf(popNum1), "");
            }
        });

        popCancleNum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopwindowNumber.dismiss();
            }
        });

    }

    private AlertDialog.Builder mNormalDialog;

    private void showDeleteItem(final ShopCarBean.ListBean dataBean) {

        mNormalDialog = new AlertDialog.Builder(this);
        mNormalDialog.setMessage("该数据删除后将无法恢复，请确认是否要删除?");
        mNormalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteItem(dataBean);
                    }
                });
        mNormalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
        // 显示
        mNormalDialog.show();
    }

    private void deleteItem(final ShopCarBean.ListBean dataBean) {
        HttpManager.instance()
                .deleteShopCar(dataBean.getId(), dataBean.getGuid())
                .subscribe(new ErrorHandleSubscriber<String>() {
                    @Override
                    public void onNext(@NonNull String integer) {
                        getDataForService();
                    }
                });
    }

    private void postDataToService(final ShopCarBean.ListBean dataBean, final String num, String price) {
        HttpManager.instance()
                .updateShopCar(dataBean.getMatid(), dataBean.getGuid(), num, price)
                .subscribe(new ErrorHandleSubscriber<GuidBean>() {
                    @Override
                    public void onNext(@NonNull GuidBean s) {
                        getDataForService();
                    }
                });
    }

    @OnClick(R.id.btn_submit)
    public void submit() {
        if (isNext) {
            Intent intent = new Intent(this, SubmitOrderActivity.class);
            startActivity(intent);
            finish();
        } else {
            TsUtils.showToast("请添加购物车");
            finish();
        }
    }

}
